package com.stefanie.nettydemo.test1;

import com.stefanie.nettydemo.utils.ByteBufferUtil;

import java.nio.ByteBuffer;

/**
 * @author:stefanie-zy
 * @time:2023/12/5-8:57
 * @description: 粘包半包分析
 */
public class Exam1 {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(50);
        String message1 = "StefanieSun\n19770721\nStefanie-zy";
        String message2 = "Quietly_zy\n";
        buffer.put(message1.getBytes());
        split(buffer);
        buffer.put(message2.getBytes());
        split(buffer);
    }

    private static void split(ByteBuffer buffer) {
        // 读模式
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                // 计算长度
                int length = i + 1 - buffer.position();
                // 设置内存空间
                ByteBuffer target = ByteBuffer.allocate(length);
                // 写入
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get(j));
                }
                ByteBufferUtil.debugAll(target);
            }
        }

        // 读完之后从头开始
        buffer.compact();
    }
}
